from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView
# from mall import settings
from QQLoginTool.QQtool import OAuthQQ
# class QQAuthURLview(APIView):
#
#     def get(self,request):
#
#         url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=test"
#         return Response({'login_url':url})

# 弹出第三方页面
from oauth.models import OAuthQQUser
from oauth.serializers import AuthQQUserSerialzier
from oauth.utils import generic_access_token


class QQAuthURLView(APIView):

    def get(self,request):

        state = '/'
        oAuth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=state)
        url = oAuth.get_qq_url()
        return Response({'login_url':url})

#回调页面    https://graph.qq.com/oauth2.0/token
class AuthQQUserView(APIView):
    def get(self,request):
        code = request.query_params.get('code')
        if code is None:
            return Response(status=status.HTTP_404_NOT_FOUND)

        oAuth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,)
        access_token = oAuth.get_access_token(code)
        open_id = oAuth.get_open_id(access_token)


#根据open_id判断用户是否绑定
        try:
            qquser = OAuthQQUser.objects.get(openid=open_id)
        except OAuthQQUser.DoesNotExist:


            #确保openid在安全的环境下，即进行加密
            access_token = generic_access_token(open_id)
            return Response({'access_token':access_token})
        else:
            #没有异常，说明用户绑定过，跳转首页，返回token
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'token':token,
                'username':qquser.user.username,
                'id':qquser.user.id
            })

    def post(self,request):
        """
        功能描述：openid绑定用户
        1接受数据
        2检测数据
          短信验证码
          openid
          用户名
        3保存
        4犯会响应
        """

        # 1接受数据
        data = request.data
        # 2检测数据
        seriliazer = AuthQQUserSerialzier(data=data)
        seriliazer.is_valid(raise_exception=True)
        #   短信验证码
        #   openid
        #   用户名
        # 3保存
        qquser = seriliazer.save()
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)
        # 4返回响应
        return Response({
            'token': token,
            'username': qquser.user.username,
            'user_id': qquser.user.id
        })














